package com.gem.talkbase.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.gem.talkbase.R;
import com.gem.talkbase.activity.ChangePassActivity;
import com.gem.talkbase.activity.FeedBackActivity;
import com.gem.talkbase.activity.FirendRing_Activity;
import com.gem.talkbase.activity.Fragment_setting_try;
import com.gem.talkbase.activity.LocationPeople;
//import com.gem.talkbase.activity.LocationPeople;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.util.DialogUtil;
import com.gem.talkbase.util.StreamTools;
import com.gem.talkbase.widget.TitleView;

import android.R.string;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;


/**
 * 
 * 功能描述：发现fragment页面
 */
public class Fragment_find extends Fragment implements OnClickListener, AMapLocationListener, Runnable{

	private View mParent;

	private FragmentActivity mActivity;

	private TitleView mTitle;

	private View mchangePass,firendring;

	/*-------------------------------------my do-----------------------------------*/
	private View fragment_find_try;
	/*-------------------------------------定位-----------------------------------*/
	private LocationManagerProxy aMapLocManager = null;
	private TextView myLocation;
	private AMapLocation aMapLocation;// 用于判断定位超时
	private double getlng,getlat;
	private String URL_LOCATION =Client.URL_LOCATION;
	SharedPreferences sharedPreferences; //获得登录者的id

	private String URL_GETALLID = Client.URL_GETALLID;


	private Handler handler = new Handler(){

		@Override

		public void handleMessage(Message msg) {

			switch(msg.what){

			case 1:

				Bundle data = msg.getData();  
				String fujinpeople = data.getString("result");  
				//Toast.makeText(getActivity(), "附近的人获取成功！", 0).show();
				System.out.println("附近的人获取成功！........"+fujinpeople);
				Intent intent = new Intent(getActivity(),LocationPeople.class);
				intent.putExtra("fujinpeople",fujinpeople);

				getActivity().startActivity(intent);
				break ;

			case 2:   
				//Toast.makeText(getActivity(), "附近的人获取失败！", 0).show();
				break ;


			case 3:
				Bundle data3 = msg.getData();  
				String getallid = data3.getString("result");  
				//startActivity(new Intent(getActivity(), Fragment_setting_try.class));			
				Intent intent3 = new Intent(getActivity(),Fragment_setting_try.class);
				intent3.putExtra("getallid",getallid);
				getActivity().startActivity(intent3);
				break;
			case 4:
				Toast.makeText(getActivity(), "没有网络，玩不了哦！", 0).show();
				break;
			}
		}
	};

	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
	public static Fragment_find newInstance(int index) {
		Fragment_find f = new Fragment_find();

		// Supply index input as an argument.
		Bundle args = new Bundle();
		args.putInt("index", index);
		f.setArguments(args);

		return f;
	}

	public int getShownIndex() {
		return getArguments().getInt("index", 0);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_find, container, false);
		//获得登录者的信息
		sharedPreferences =getActivity().getSharedPreferences(Client.SAVE_USER,getActivity().MODE_PRIVATE);







		firendring=view.findViewById(R.id.displaySetting);
		firendring.setOnClickListener(this);//=====================================================================================
		//
		//		mchangePass=view.findViewById(R.id.displaySetting1);
		//		mchangePass.setOnClickListener(this);

		mchangePass=view.findViewById(R.id.displaySetting2);
		mchangePass.setOnClickListener(this);

		fragment_find_try=view.findViewById(R.id.fragment_find_try);
		fragment_find_try.setOnClickListener(this);



		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mParent = getView();
		mActivity = getActivity();

		mTitle = (TitleView) mParent.findViewById(R.id.title);
		mTitle.setTitle(R.string.title_settings);
		//		mTitle.setLeftButton(R.string.back, new OnLeftButtonClickListener() {
		//
		//			@Override
		//			public void onClick(View button) {
		//			}
		//		});
		//		mTitle.hiddenLeftButton();
		//		mTitle.setRightButton(R.string.help, new OnRightButtonClickListener() {
		//
		//			@Override
		//			public void onClick(View button) {
		//			}
		//		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub


		switch (v.getId()) {
		case R.id.displaySetting:
			startActivity(new Intent(getActivity(), FirendRing_Activity.class));
			break;//=====================================================================================================================
			//		case R.id.displaySetting1:
			//			startActivity(new Intent(getActivity(), ChangePassActivity.class));
			//			break;
		case R.id.displaySetting2:
			String userid = sharedPreferences.getString("userid", ""); 


			/*--------------------------------定位----------------------------------------*/
			aMapLocManager = LocationManagerProxy.getInstance(getActivity());
			/*
			 * mAMapLocManager.setGpsEnable(false);//
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 */
			aMapLocManager.requestLocationUpdates(
					LocationProviderProxy.AMapNetwork, 2000, 10, Fragment_find.this);
			handler.postDelayed(this, 12000);// 设置超过12秒还没有定位到就停止定位


			toServlet(userid);//点击附近的人的按钮，在传经纬度上去后返回了好友的信息
			System.out.println("hcy=================userid============="+userid);
			//startActivity(new Intent(getActivity(), LocationPeople.class));
			break;
		case R.id.fragment_find_try:
			String userid1 = sharedPreferences.getString("userid", ""); 


			getallid(userid1);
			//startActivity(new Intent(getActivity(), Fragment_setting_try.class));
			break;	


		}

	}





	/*-----------------------------------------定位----------------------------------------*/	

	@Override
	public void onPause() {
		super.onPause();
		stopLocation();// 停止定位
	}

	/**
	 * 销毁定位
	 */
	private void stopLocation() {
		if (aMapLocManager != null) {
			aMapLocManager.removeUpdates(this);
			aMapLocManager.destory();
		}
		aMapLocManager = null;
	}

	/**
	 * 此方法已经废弃
	 */
	@Override
	public void onLocationChanged(Location location) {
	}

	@Override
	public void onProviderDisabled(String provider) {

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	/**
	 * 混合定位回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation location) {
		if (location != null) {
			this.aMapLocation = location;// 判断超时机制
			Double geoLat = location.getLatitude();
			Double geoLng = location.getLongitude();
			String cityCode = "";
			String desc = "";
			Bundle locBundle = location.getExtras();
			if (locBundle != null) {
				cityCode = locBundle.getString("citycode");
				desc = locBundle.getString("desc");
			}
			/*String str = ("定位成功:(" + geoLng + "," + geoLat + ")"
					+ "\n精    度    :" + location.getAccuracy() + "米"
					+ "\n定位方式:" + location.getProvider() + "\n定位时间:"
					+ AMapUtil.convertToTime(location.getTime()) + "\n城市编码:"
					+ cityCode + "\n位置描述:" + desc + "\n省:"
					+ location.getProvince() + "\n市:" + location.getCity()
					+ "\n区(县):" + location.getDistrict() + "\n区域编码:" + location
					.getAdCode());
			myLocation.setText(str);*/


			getlng = geoLng;
			getlat = geoLat;

			System.out.println("==========================="+getlng);
			System.out.println("==========================="+getlat);
		}
	}

	@Override
	public void run() {
		if (aMapLocation == null) {
			//ToastUtil.show(this, "12秒内还没有定位成功，停止定位");
			//Toast.makeText(getActivity(), "12秒内还没有定位成功，停止定位", Toast.LENGTH_LONG).show();
			//myLocation.setText("12秒内还没有定位成功，停止定位");
			stopLocation();// 销毁掉定位
		}
	}




	/*-----------------------------------http传经纬度到服务器，并返回附近人的信息----------------------------------------------------*/	

	public void toServlet(final String str){
		new Thread(new Runnable() {
			public void run(){
				try {

					System.out.println("...str..location...."+str);
					String lng = getlng+"";
					String Lat = getlat+"";


					HttpClient client = new DefaultHttpClient();

					//提交数据的路径
					HttpPost httpPost =new HttpPost(URL_LOCATION);

					httpPost.addHeader("charset", HTTP.UTF_8);

					//指定要提交数据的实体
					List<NameValuePair> parameters = new ArrayList<NameValuePair>();

					System.out.println("getlng........"+getlng);

					System.out.println("getlat........"+getlat);

					parameters.add( new BasicNameValuePair("getlng", URLEncoder.encode(lng,"utf-8")));//性别。。。。

					parameters.add( new BasicNameValuePair("getlat", URLEncoder.encode(Lat,"utf-8")));//我的个性签名。。。。

					parameters.add( new BasicNameValuePair("username", URLEncoder.encode(str,"utf-8")));//我的唯一id。。。。

					//parameters.add( new BasicNameValuePair("act", "act_mydata"));//提交 到服务器的if判断。。。。

					httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
					System.out.println("get...lng..lat............");
					HttpResponse response = client.execute(httpPost);
					int code = response.getStatusLine().getStatusCode();//获得返回码，为200是则表示提交且返回成功
					System.out.println("code..madata........."+code);

					if (code == 200) {


						InputStream is = response.getEntity().getContent();
						String 	result = StreamTools.readInputStream(is); //获取从服务器拿到的数据
						//System.out.println("result..<><><><><>..."+result);
						//请求成功则返回的文本信息

						Message msg = new Message() ;

						//这三句可以传递数据  
						Bundle data = new Bundle();  
						data.putString("result", result);//COUNT是标签,handleMessage中使用  
						msg.setData(data);  

						if(result!=null&&result!=""){ //如果拿到的为真，则打印一个toase

							msg.what = 1 ;

							Fragment_find.this.handler.sendMessage(msg);





						}else{

							msg.what = 2 ;

							Fragment_find.this.handler.sendMessage(msg);

						}

					}  

				} catch (UnsupportedEncodingException e) {

					e.printStackTrace();

				} catch (ClientProtocolException e) {

					e.printStackTrace();

				} catch (IOException e) {

					e.printStackTrace();

				}


				//Toast.makeText(Setinformation_mydata.this, "ok", 0).show();

			}


		}).start();
	}	






	public void getallid(final String str){
		new Thread(new Runnable() {
			public void run(){
				try {
					HttpClient client = new DefaultHttpClient();
					//提交数据的路径
					HttpPost httpPost =new HttpPost(URL_GETALLID);
					httpPost.addHeader("charset", HTTP.UTF_8);
					//指定要提交数据的实体
					List<NameValuePair> parameters = new ArrayList<NameValuePair>();
					parameters.add( new BasicNameValuePair("username", URLEncoder.encode(str,"utf-8")));//我的唯一id。。。。
					httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
					HttpResponse response = client.execute(httpPost);
					int code = response.getStatusLine().getStatusCode();//获得返回码，为200是则表示提交且返回成功
					System.out.println("code..madata........."+code);
					if (code == 200) {
						InputStream is = response.getEntity().getContent();
						String 	result = StreamTools.readInputStream(is); //获取从服务器拿到的数据

						Message msg = new Message() ;

						//这三句可以传递数据  
						Bundle data = new Bundle();  
						data.putString("result", result);//COUNT是标签,handleMessage中使用  
						msg.setData(data);  
						if(result!=null&&result!=""){ //如果拿到的为真，则打印一个toase

							msg.what = 3 ;

							Fragment_find.this.handler.sendMessage(msg);

						}else{

							msg.what = 4 ;

							Fragment_find.this.handler.sendMessage(msg);

						}

					}  

				} catch (UnsupportedEncodingException e) {

					e.printStackTrace();

				} catch (ClientProtocolException e) {

					e.printStackTrace();

				} catch (IOException e) {

					e.printStackTrace();

				}

			}


		}).start();

	}














}